// services/database_service.dart
import 'package:mysql1/mysql1.dart';
import 'dart:async';
import 'activation_service.dart';

class DatabaseService {
  static final DatabaseService _instance = DatabaseService._internal();
  factory DatabaseService() => _instance;
  DatabaseService._internal();

  MySqlConnection? _connection;
  bool _isConnecting = false;

  // 数据库配置
  final ConnectionSettings _settings = ConnectionSettings(
    host: 'cd-cynosdbmysql-grp-eottlnti.sql.tencentcdb.com',
    port: 24113,
    user: 'root',
    password: 'Yhyx8888',
    db: 'yhyxd',
  );

  Future<MySqlConnection?> get connection async {
    if (_connection != null) {
      // 检查连接是否仍然有效
      try {
        // 执行一个简单的查询来测试连接
        await _connection!.query('SELECT 1');
        return _connection;
      } catch (e) {
        // 连接已断开，重新连接
        _connection = null;
      }
    }
    
    await _connect();
    return _connection;
  }

  Future<void> _connect() async {
    if (_isConnecting) return;
    
    _isConnecting = true;
    try {
      _connection = await MySqlConnection.connect(_settings);
      print('数据库连接成功');
    } catch (e) {
      print('数据库连接失败: $e');
      _connection = null;
    } finally {
      _isConnecting = false;
    }
  }

  Future<void> disconnect() async {
    try {
      await _connection?.close();
      _connection = null;
      print('数据库连接已关闭');
    } catch (e) {
      print('关闭数据库连接失败: $e');
    }
  }

  // 检查激活码
  Future<ActivationResult> checkActivationCode(String code) async {
    try {
      // // 临时使用模拟数据测试（先注释掉数据库连接）
      // await Future.delayed(Duration(seconds: 1)); // 模拟网络延迟
      
      // // 模拟验证逻辑
      // if (code.startsWith('ACT') && code.length > 5) {
      //   final expireTime = DateTime.now().add(Duration(days: 30));
      //   return ActivationResult(
      //     success: true,
      //     expireTime: expireTime,
      //     activationCode: code,
      //   );
      // } else {
      //   return ActivationResult(
      //     success: false,
      //     message: '激活码无效',
      //   );
      // }
      
      
      // 原来的数据库代码（暂时注释掉）
      final conn = await connection;
      if (conn == null) {
        return ActivationResult(
          success: false,
          message: '数据库连接失败',
        );
      }

      // 查询激活码
      final results = await conn.query(
        'SELECT code, expire_time FROM activation WHERE code = ?',
        [code],
      );

      if (results.isEmpty) {
        return ActivationResult(
          success: false,
          message: '激活码无效',
        );
      }

      final row = results.first;
      final String dbCode = row[0] as String;
      final DateTime expireTime = row[1] as DateTime;

      // 检查过期时间
      final currentTime = DateTime.now();
      if (expireTime.isBefore(currentTime)) {
        return ActivationResult(
          success: false,
          message: '激活码已过期',
        );
      }

      return ActivationResult(
        success: true,
        expireTime: expireTime,
        activationCode: dbCode,
      );
      
    } catch (e) {
      print('数据库查询错误: $e');
      return ActivationResult(
        success: false,
        message: '数据库错误: $e',
      );
    }
  }

  Future<void> dispose() async {
    await disconnect();
  }
}